package com.xiao.permission_system.security;

import com.xiao.permission_system.entity.Role;
import com.xiao.permission_system.entity.UserInfo;
import com.xiao.permission_system.entityvo.RoleVO;
import com.xiao.permission_system.mapper.UserInfoMapper;
import com.xiao.permission_system.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*
          1 通过username获取到userInfo信息
          2 通过User(username,password,authorities)返回UserDetails
         */
        UserInfo userInfo = userInfoService.findByusername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("NOT FOUND");
        }
        // 定义权限列表
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        // 用户拥有的权限
        for (RoleVO role : userInfoMapper.getRoles(userInfo.getId())) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        User userDetails = new User(userInfo.getUsername(), bCryptPasswordEncoder.encode(userInfo.getPassword()), authorities);
        return userDetails;
    }
}
